<?php

declare (strict_types=1);

namespace app\common\service\redis;

use think\cache\driver\Redis;

/**
 * Class RedisService 缓存队列服务（继承tp6原来的redis入口，之前方法都能用）
 * @package app\common\service
 * Author FashionJune
 */
class RedisQueueService extends Redis
{

    public static function init(){
        return new static();
    }

    public $is_json = true;


    public function set_json($set = true)
    {
        $this->is_json = $set;
    }

    function __construct(array $options = [])
    {
        $options['host'] = env('REDIS_HOST');
        $options['port'] = env('REDIS_PORT');
        $options['password'] = env('REDIS_PASSWORD');
        $options['tag_prefix'] = env('REDIS_PREFIX');
        parent::__construct($options);
    }

    /**
     * @title 左侧插入队列
     * @param $key
     * @param mixed ...$values
     * @author FashionJune
     */
    public function lpush($key, ...$values)
    {
        foreach ($values as &$value) {
            $value = is_array($value) ? json_encode($value) : $value;
        }
        $this->handler->lPush($key, ...$values);
    }

    /**
     * @title 右侧插入队列
     * @param $key
     * @param mixed ...$values
     * @author FashionJune
     */
    public function rpush($key, ...$values)
    {
        foreach ($values as &$value) {
            $value = is_array($value) ? json_encode($value) : $value;
        }
        $this->handler->rPush($key, ...$values);
    }

    /**
     * @title 正序读取队列
     * @param $key
     * @param int $start
     * @param int $end
     * @return array
     * @author FashionJune
     */
    public function list($key, $start = 0, $end = -1)
    {
        $list = $this->handler->lRange($key, $start, $end);
        if ($this->is_json) {
            foreach ($list as &$value) {
                $value = json_decode($value, true);
            }
        }
        return $list;
    }

    /**
     * @title 获取队列长度
     * @param string $key
     * @return bool|int
     * @author FashionJune
     */
    public function length(string $key)
    {
        return $this->handler->lLen($key);
    }

    /**
     * @title 左侧获取并删除一个元素
     * @param string $key
     * @return mixed|void
     * @author FashionJune
     */
    public function lpull(string $key)
    {
        $value = $this->handler->lRange($key, 0, 0);
        if (!isset($value[0])) {
            return false;
        }
        $value = $value[0];
        $this->lpop($key);
        return $this->is_json ? json_decode($value, true) : $value;
    }


    /**
     * @title 左侧删除一个元素
     * @param string $key
     * @author FashionJune
     */
    public function lpop(string $key)
    {
        $this->handler->lPop($key);
    }

    /**
     * @title 右侧删除一个元素
     * @param string $key
     * @author FashionJune
     */
    public function rpop(string $key)
    {
        $this->handler->rPop($key);
    }

}